<?php

namespace app\admin\model;
use app\api\model\OrderAction;
use app\api\model\OrderShipLog;
use think\exception\PDOException;
use think\Model;

class OrderModel extends Model
{
    protected $name = 'order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    /**
     * 根据搜索条件获取轮播列表信息
     */
    public function getDataByWhere($map, $Nowpage, $limits)
    {
        return $this->alias('p')->field('p.*,think_member.nickname')->join('think_member','p.uid = think_member.id','LEFT')->where($map)->page($Nowpage, $limits)->order('p.add_time desc')->select();
    }




    public function refundOrder($param)
    {
        try{
            $data = [
                'order_status' => 6,
                'refund_time' =>time(),
                'refund_desc' =>$param['refund_desc'],
            ];
            if($param['check_refund'] == 2) $data['order_status'] = 7;
            $oo = $this->find($param['id']);
            if(!$oo) return ['code' => -1, 'data' => '', 'msg' => '订单不存在'];
            if($oo->pay_status != 1) return ['code' => -1, 'data' => '', 'msg' => '订单未支付不能退款！'];
            $result = $this->allowField(true)->save($data,['id'=>$param['id']]);
            if(false === $result){
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                //增加操作记录
                $msg = [6=>'通过',7=>'驳回'];
                db('order_action')->insert([
                    'order_id' => $param['id'],
                    'action_user' => session('uid'),
                    'order_status' => $data['order_status'],
                    'action_note' => session('username').'后台操作订单退款申请,状态：'.$msg[$data['order_status']].')',
                    'log_time' => time(),
                ]);
                return ['code' => 1, 'data' => '', 'msg' => '成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }





    public function exportOrder($form_data)
    {
        set_time_limit(0);
        //判断导出条件是否全为空
        $flag=false;
        $result = $this;
        foreach($form_data as $k =>$v)
        {
            if($v)
            {
                $flag=true;
                break;
            }
        }
        if($flag===false) return ['code' => -1, 'data' => '', 'msg' => '请选择导出条件'];
        if(isset($form_data['nickname']) && !empty($form_data['nickname']))
        {
            $result = $result->where('think_member.nickname','like','%'.$form_data['nickname'].'%');
        }

        if(isset($form_data['sn']) && !empty($form_data['sn']))
        {
            $result = $result->where('think_order.order_sn','like','%'.$form_data['sn'].'%');
        }

        if(isset($form_data['order_status']) && !empty($form_data['order_status']))
        {
            $result = $result->where('think_order.order_status','=',$form_data['order_status']);
        }

        if(isset($form_data['order_type']) && !empty($form_data['order_type']))
        {
            $result = $result->where('think_order.order_type','=',$form_data['order_type']);
        }

        if(isset($form_data['pay_type']) && !empty($form_data['pay_type']))
        {
            $result = $result->where('think_order.pay_type','=',$form_data['pay_type']);
        }

        if(isset($form_data['add_time']) && !empty($form_data['add_time']))
        {
            $tt = explode('~',$form_data['add_time']);
            // ['between',[strtotime(trim($tt[0])),strtotime(trim($tt[1]).' 23:59:59')]];
            $result = $result->where('think_order.add_time','between',[strtotime(trim($tt[0])),strtotime(trim($tt[1]).' 23:59:59')]);
        }

        $status = ['-1'=>'待支付','1'=>'已支付'];
        $pay_type = ['1'=>'微信','2'=>'支付宝','3'=>'code'];
        $order_type = ['1'=>'测评订单','2'=>'会员订单','3'=>'团购订单','4'=>'code订单','5'=>'无需支付订单','6'=>'解析订单'];
        $result = $result->field('think_order.*')->join('think_member','think_order.uid = think_member.id','LEFT')->select();

        $sum=1;
        $sumArray=[];
        $arr = [];
        foreach ($result as $k=>$v){
            $goods_num=db('order_question')->where('order_id',$v['id'])->select();
            $nn_1 = db('order_question')->where('order_id',$v['id'])->count();
            for ($i=0;$i<$nn_1;$i++){
                $arr[$sum+$i]['order_sn']=$v->order_sn;
                $arr[$sum+$i]['order_type']=$order_type[$v->order_type]??'';
                $arr[$sum+$i]['pay_type']=$pay_type[$v->pay_type]??'';
                $arr[$sum+$i]['name']=$goods_num[$i]['name'];
                $arr[$sum+$i]['price']=$goods_num[$i]['price'];
                $arr[$sum+$i]['num']=$goods_num[$i]['num'];
                $arr[$sum+$i]['all_price']=$v->total_amount;
                $arr[$sum+$i]['add_time']=$v->add_time==0?'-':date('Y-m-d H:i:s',$v->add_time);
                $arr[$sum+$i]['pay_time']=$v->pay_time==0?'-':date('Y-m-d H:i:s',$v->pay_time);
                $arr[$sum+$i]['order_status']=$status[$v->order_status];
            }
            if($nn_1>1){
                array_push($sumArray,[$sum+1,$sum+=$nn_1]);
            }
            else{
                $sum+=1;
            }
        }
        //dump($arr);die;
        $xlsTitle = iconv('utf-8', 'gb2312', '订单信息');//文件名称
        $filename = '订单信息 - 【操作人:'. session('username').' ( '.date("Y-m-d").' )】';
        $count=count($arr);
        //$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        //导出
        $path = dirname(__FILE__); //找到当前脚本所在路径
        vendor("PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.IOFactory");
        /*vendor("PHPExcel.PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.Writer.IWriter");
        vendor("PHPExcel.PHPExcel.Writer.Abstract");
        vendor("PHPExcel.PHPExcel.Writer.Excel5");
        vendor("PHPExcel.PHPExcel.Writer.Excel2007");
        vendor("PHPExcel.PHPExcel.IOFactory");*/
        $objPHPExcel = new \PHPExcel();


        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);



        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('H1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('I1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('J1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('K1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('H1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('I1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('J1')->getFont()->setName('宋体') ->setSize(12)->setBold(true);





        // 设置表头信息
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '订单类型')
            ->setCellValue('C1', '支付方式')
            ->setCellValue('D1', '名称')
            ->setCellValue('E1', '成交单价')
            ->setCellValue('F1', '订购数量')
            ->setCellValue('G1', '成交金额')
            ->setCellValue('H1', '下单时间')
            ->setCellValue('I1', '支付时间')
            ->setCellValue('J1', '订单状态');



        /*--------------开始从数据库提取信息插入Excel表中------------------*/

        foreach ($sumArray as $k=>$v)
        {
            $objPHPExcel->getActiveSheet(0)->mergeCells('A'.$v[0].':A'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('B'.$v[0].':B'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('C'.$v[0].':C'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('D'.$v[0].':D'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('E'.$v[0].':E'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('F'.$v[0].':F'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('K'.$v[0].':K'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('L'.$v[0].':L'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('M'.$v[0].':M'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('N'.$v[0].':N'.$v[1]);
            $objPHPExcel->getActiveSheet(0)->mergeCells('O'.$v[0].':O'.$v[1]);

        }


        //dump($arr);die;
        //$i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
        for ($i = 2; $i <= $count+1; $i++) {
            $objPHPExcel->getActiveSheet(0)->setCellValue('A' . $i, $arr[$i-1]['order_sn']);
            $objPHPExcel->getActiveSheet(0)->getStyle('A' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . $i, $arr[$i-1]['order_type']);
            $objPHPExcel->getActiveSheet(0)->getStyle('B' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('C' . $i, $arr[$i-1]['pay_type']);
            $objPHPExcel->getActiveSheet(0)->getStyle('C' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


            $objPHPExcel->getActiveSheet(0)->setCellValue('D' . $i, $arr[$i-1]['name']);
            $objPHPExcel->getActiveSheet(0)->getStyle('D' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('E' . $i, $arr[$i-1]['price']);
            $objPHPExcel->getActiveSheet(0)->getStyle('E' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('F' . $i, $arr[$i-1]['num']);
            $objPHPExcel->getActiveSheet(0)->getStyle('F' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('G' . $i, $arr[$i-1]['all_price']);
            $objPHPExcel->getActiveSheet(0)->getStyle('G' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


            $objPHPExcel->getActiveSheet(0)->setCellValue('H' . $i, $arr[$i-1]['add_time']);
            $objPHPExcel->getActiveSheet(0)->getStyle('H' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->getActiveSheet(0)->setCellValue('I' . $i, $arr[$i-1]['pay_time']);
            $objPHPExcel->getActiveSheet(0)->getStyle('I' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $objPHPExcel->getActiveSheet(0)->setCellValue('J' . $i, $arr[$i-1]['order_status']);
            $objPHPExcel->getActiveSheet(0)->getStyle('J' . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        }


        /*--------------下面是设置其他信息------------------*/

        $objPHPExcel->getActiveSheet(0)->setTitle('订单信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置


        // $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        ob_end_clean();

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$filename.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        /*header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=$filename");
        header('Cache-Control: max-age=0');
        //header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $objWriter->save('php://output');*/
        exit;
    }


    // 过滤掉emoji表情
    public function filter_Emoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }


}